package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.MymachineAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.MymachineBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
  * create an instance of this fragment.
 */
public class MymachineFragment extends Fragment implements ListViewPlus.ListViewPlusListener{
    private int mmCode;
    private String TAG="MymachineFragment";
    private int count,page_count,page_index;
    private LinearLayout linearLayout;
    private ListViewPlus mListView;
    private MymachineBean mMymachineBean;
    private MymachineAdapter mMymachineAdapter;
    private List<MymachineBean> MymachineBeanList = new ArrayList<>();
    private String sn;


    @Override
    public void onRefresh() {
        MymachineBeanList.clear();
        intView();
        mMymachineAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if(page_index<page_count){
             Log.e(TAG, "page_index:"+page_index);
            loadData(ListViewPlus.LOAD);
        }else{
            Toast.makeText(getContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    Log.e(TAG, "onRefresh:");
                    //intView();
                    onLoadComplete();
                    Toast.makeText(getContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Log.e(TAG, "onLoadMore:");
                    loadMode(page_index);
                    break;
            }

        }

    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }


    private void loadMode(int page_index){
        SharedPreferences sharedPreferences =  getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/is_binding");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mmCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                     JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        String bindingTime = value.getString("bindingTime");
                        String desc = value.getString("desc");
                        String pId = value.getString("pId");
                        mMymachineBean = new MymachineBean(sn,bindingTime,desc,pId);
                        MymachineBeanList.add(mMymachineBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (mmCode == 200) {
                    //mMymachineAdapter = new MymachineAdapter(getContext().getApplicationContext(),MymachineBeanList);
                    mMymachineAdapter.notifyDataSetChanged();
                   // mListView.setAdapter(mMymachineAdapter);
                }

                if (mmCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }



            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                if(MymachineBeanList.size()==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else{
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });
    }

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_mymachine, container, false);
        mListView=view.findViewById(R.id.mymachine_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        linearLayout=view.findViewById(R.id.no_mymachine);
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
             @Override
             public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                 ListViewPlus listView = (ListViewPlus) parent;
                 MymachineBean mSnListBean = (MymachineBean) listView.getItemAtPosition(position);
                 sn = mSnListBean.getSn();
                 dialog_show();

                 return false;
             }
         });
        intView();
        return view;
    }

    private void dialog_show() {
        MymachineFragment.CustomPopup customPopup = new MymachineFragment.CustomPopup(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();
    }

    public class CustomPopup extends CenterPopupView {

        private TextView mytextView, banlance_resout;

        public CustomPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.banlance_custom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            banlance_resout = findViewById(R.id.banlance_resout);
            banlance_resout.setText("解绑");
            mytextView = findViewById(R.id.balance_tishi);
            mytextView.setText(sn);
            findViewById(R.id.banlance_dialog_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    outofBinding();
                    dismiss();
                }
            });
        }

        protected void onShow() {
            super.onShow();
        }
    }

    private void outofBinding(){
        SharedPreferences sharedPreferences =  getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/cancel_binding");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("sn", sn);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mmCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mmCode == 200) {


                }
                if (mmCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
                if (mmCode == 404) {
                    Toast.makeText(getContext().getApplicationContext(), "解绑失败", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }



            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                MymachineBeanList.clear();
                intView();
            }
        });
    }




    private void intView() {
        SharedPreferences sharedPreferences =  getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/is_binding");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mmCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                        count= jsonObjec.optInt("count", 0);
                        page_count= jsonObjec.optInt("page_count", 0);
                        page_index= jsonObjec.optInt("page_index", 0);

                    }
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        String bindingTime = value.getString("bindingTime");
                        String desc = value.getString("desc");
                        String pId = value.getString("pId");
                        mMymachineBean = new MymachineBean(sn,bindingTime,desc,pId);
                        MymachineBeanList.add(mMymachineBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (mmCode == 200) {
                    mMymachineAdapter = new MymachineAdapter(getContext().getApplicationContext(),MymachineBeanList);
                    mMymachineAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mMymachineAdapter);
                }

                if (mmCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }



            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                if(MymachineBeanList.size()==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else{
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });
    }


}
